<template>
    <div>
        <app-head></app-head>
        <app-body>
            <el-row>
                <el-col :span="4" class="sidebar">
                    <el-menu :default-active="labelName.toString()"  class="el-menu-vertical-demo" @select="handleMenuSelect">
                        <el-menu-item
                            v-for="item in categoryList"
                            :key="item.id"
                            :index="item.id.toString()">
                            {{item.name}}
                        </el-menu-item>
                    </el-menu>
                </el-col>
                <el-col :span="20" class="main-content">
                    <div class="content">
                        <!-- ✅ 筛选区域插入这里 -->
                        <div class="filter-bar" style="margin-bottom: 20px; display: flex; align-items: center; flex-wrap: wrap; gap: 20px;">
                            <!-- 发布时间筛选 -->
                            <el-select v-model="selectedTime" placeholder="发布时间" @change="handleFilterChange" style="width: 140px;">
                                <el-option label="最新" value="newest"></el-option>
                                <el-option label="1天内" value="1day"></el-option>
                                <el-option label="3天内" value="3days"></el-option>
                            </el-select>

                            <!-- 热门商品（只支持降序） -->
                            <el-button
                                type="primary"
                                :plain="!sortByHot"
                                @click="toggleHotSort"
                            >
                                <i v-if="sortByHot" class="el-icon-check" style="margin-right: 4px;"></i>
                                热门商品
                            </el-button>

                            <!-- 价格排序和区间 -->
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <el-select v-model="priceSort" placeholder="价格排序" @change="handleFilterChange" style="width: 120px;">
                                    <el-option label="价格升序" value="asc"></el-option>
                                    <el-option label="价格降序" value="desc"></el-option>
                                </el-select>
                                <!-- 最低价 -->
                                <el-input
                                    v-model="minPrice"
                                    placeholder="最低价"
                                    @change="handleFilterChange"
                                    style="width: 100px;">
                                    <template #prefix>
                                        <span style="display: flex; align-items: center; height: 100%; color: #606266;">￥</span>
                                    </template>
                                </el-input>

                                <span>-</span>

                                <!-- 最高价 -->
                                <el-input
                                    v-model="maxPrice"
                                    placeholder="最高价"
                                    @change="handleFilterChange"
                                    style="width: 100px;">
                                    <template #prefix>
                                        <span style="display: flex; align-items: center; height: 100%; color: #606266;">￥</span>
                                    </template>
                                </el-input>
                            </div>
                        </div>
                        <div class="idle-list">
                            <el-row :gutter="30">
                                <el-col :span="6" v-for="(item, index) in idleList" :key="index">
                                    <!-- 每个物品卡 -->
                                    <div class="idle-card" @click="toDetails(item)">
                                        <el-image
                                            class="idle-image"
                                            :src="item.images"
                                            fit="cover">
                                            <div slot="error" class="image-slot">
                                                <i class="el-icon-picture-outline">无图</i>
                                            </div>
                                        </el-image>
                                        <div class="idle-content">
                                            <div class="idle-title">{{ item.productName }}</div>
                                            <div class="idle-description">{{ item.productDescription }}</div>
                                            <div class="idle-price">
                                                <span class="price-symbol">￥</span>
                                                <span class="price-number">{{ item.productPrice }}</span>
                                            </div>
                                            <div class="idle-viewcount" style="font-size: 12px; color: #888; margin-top: 4px;">
                                                👁️浏览量：{{ item.viewCount || 0 }}
                                            </div>
                                        </div>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                        <!-- 外层容器,用于包裹分页组件，方便样式控制-->
                        <div class="pagination">
                            <!-- Element UI 的分页组件，用来展示分页条和控制翻页 -->
                            <el-pagination
                                background
                                @current-change="handleCurrentChange"
                                :current-page.sync="currentPage"
                                :page-size="8"
                                layout="prev, pager, next, jumper"
                                :total="totalElements">
                            </el-pagination>
                        </div>
                    </div>
                </el-col>
            </el-row>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue';
    import AppFoot from '../common/AppFoot.vue';

    export default {
        name: "index",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                labelName: '0',
                idleList: [],
                currentPage: 1,
                totalElements: 1,
                categoryList: [],
                // 筛选选项绑定变量
                selectedTime: '',      // newest / 1day / 3days
                sortByHot: false,
                priceSort: '',         // asc / desc
                minPrice: 0,
                maxPrice: 0
            };
        },
        created() {
            console.log(this.$api);
            this.findIdleItem(1);  // 加载初始商品
            this.getCategories();                 // 加载分类
        },
        //Vue 中监听路由变化的代码，用于在路由参数变化时自动刷新页面数据
        watch: {
            $route(to, from) {
                console.log("路由变化 labelName:", to.query.labelName);
                this.labelName = (to.query.labelName !== undefined && to.query.labelName !== null ? to.query.labelName : '0').toString();
                let val = parseInt(to.query.page) ? parseInt(to.query.page) : 1;
                this.currentPage = val;
                this.findIdleItem(val);
            }
        },
        methods: {
            handleFilterChange() {
                this.findIdleItem(1);
            },
            toggleHotSort() {
                this.sortByHot = !this.sortByHot;
                this.handleFilterChange();
            },
            getCategories() {
                this.$api.getAllClassification().then(res => {
                    if (res.code === 200) {
                        // this.options2 = res.data.map(item => ({
                        //     value: item.id,  // 根据后端字段名修改
                        //     label: item.name
                        // }));
                        this.categoryList = [
                            {id: '0',name: '全部'},
                            ...res.data
                        ];
                    } else {
                        this.$message.error('获取分类失败：' + res.msg);
                    }
                }).catch(() => {
                    this.$message.error('请求分类接口出错');
                });
            },
            //寻找分类某一页
            findIdleItem(page) {
                //开启加载动画
                const loading = this.$loading({
                    lock: true,//锁定页面滚动
                    text: '加载数据中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.1)'
                });
                const filters = {
                    page: page,
                    size: 8,
                    time: this.selectedTime,
                    hot: this.sortByHot,
                    priceSort: this.priceSort,
                    minPrice: this.minPrice,
                    maxPrice: this.maxPrice
                };
                //判断是否选择了某个分类，0表示全部
                if (this.labelName > 0) {
                    this.$api.findIdleItemByLable(this.labelName,filters).then(res => {
                        if (res.code === 200 && res.data && res.data.content) {
                            let list = res.data.content;
                            console.log('第一个商品 viewCount:', list[0].viewCount);
                            // 过滤只显示状态为approved的商品
                            list = list.filter(item => item.statusCheck === 'APPROVED');
                            for (let i = 0; i < list.length; i++) {
                                list[i].createdAt = list[i].createdAt.substring(0, 10) + " " + list[i].createdAt.substring(11, 19);
                                let pictureList = list[i].images ? list[i].images.split(',') : [];
                                list[i].images = pictureList.length > 0 ? pictureList[0] : '';
                            }
                            this.idleList = list;
                            this.totalElements = res.data.totalElements;
                        }
                        else{
                            let list = null;
                            this.idleList = list;
                        }
                    }).catch(e => {
                        console.log(e);
                    }).finally(() => {
                        loading.close();
                    });
                } else {
                    this.$api.findIdleItemByLable(this.labelName,filters).then(res => {
                        if (res.code === 200 && res.data && res.data.content) {
                            let list = res.data.content;
                            console.log('第一个商品 viewCount:', list[0].viewCount);
                            // 过滤只显示状态为approved的商品
                            list = list.filter(item => item.statusCheck === 'APPROVED');
                            for (let i = 0; i < list.length; i++) {
                                list[i].createdAt = list[i].createdAt.substring(0, 10) + " " + list[i].createdAt.substring(11, 19);
                                let pictureList = list[i].images ? list[i].images.split(',') : [];
                                list[i].images = pictureList.length > 0 ? pictureList[0] : '';
                            }
                            this.idleList = list;
                            this.totalElements = res.data.totalElements;
                        } else {
                            this.$message.error('加载商品失败');
                        }
                    }).catch(e => {
                        console.log(e);
                    }).finally(() => {
                        loading.close();
                    });
                }
            },
            //监听点击分类跳转页面
            handleMenuSelect(index) {
                console.log('商品的类别',index);
                this.labelName = index;
                this.$router.push({path: '/index', query: { page: 1, labelName: this.labelName } });
                this.findIdleItem(1);
            },
            //监听用户切换页码时触发的事件
            handleCurrentChange(val) {
                this.$router.replace({ query: { page: val, labelName: this.labelName } });
            },
            //跳转详情页面
            toDetails(item) {
                console.log('点击的商品数据:', item);
                // 增加浏览量
                this.$api.incrementViewCount(item.productID).then(res => {
                    if (res.code === 200) {
                        console.log('浏览量增加成功');
                    }
                }).catch(err => {
                    console.error('增加浏览量失败:', err);
                });
                // 跳转到详情页
                this.$router.push({ path: '/details', query: { productId: item.productID  } });
            }
        }
    };
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');

.el-menu-vertical-demo {
    width: 100%;
    border-right: 1px solid #e0e0e0;
    height: calc(100vh - 58px);
    overflow-y: auto;
    background-color: #f5f5f5;
}

.el-menu-item {
    font-size: 16px;
    color: #1e88e5;
    transition: color 0.3s;
}

.el-menu-item:hover {
    color: #0d47a1;
}

.el-menu-item.is-active {
    color: #0d47a1;
    background-color: #e3f2fd !important;
}

.content {
    min-height: 85vh;
    padding: 20px;
    background-color: #ffffff;
    font-family: 'Roboto', sans-serif;
}

.idle-list {
    margin: 0 20px;
}

.idle-card {
    border: 1px solid #e0e0e0;
    border-radius: 10px;
    overflow: hidden;
    cursor: pointer;
    transition: box-shadow 0.3s, transform 0.3s;
    background-color: #fff;
    height: 230px;
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
}

.idle-card:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-4px);
}

.idle-image {
    width: 100%;
    height: 140px;
    object-fit: cover;
    flex-shrink: 0;
}

.idle-content {
    flex: 1;
    padding: 12px 14px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    gap: 4px; /* 子元素之间垂直间距 */
}

.idle-title {
    font-size: 20px;
    font-weight: 700;
    color: #222;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 1.3;
}

.idle-description {
    font-size: 13px;
    color: #888;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 1.2;
}

.idle-price {
    margin-top: auto;
    font-size: 22px;
    color: #f44336;
    font-weight: bold;
    line-height: 1;
    margin-top: 1px;
    display: flex;
    align-items: baseline;
}

.price-symbol {
    font-size: 16px;
    color: #f44336;
    font-weight: bold;
    margin-right: 2px;
}

.price-number {
    font-size: 22px;
    color: #f44336;
    font-weight: bold;
}

.user-info {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.user-avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 10px;
}

.user-nickname {
    font-size: 14px;
    color: #999;
}

.pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
}

.sidebar {
    background-color: #f5f5f5;
    height: calc(100vh - 60px);
}

.main-content {
    background-color: #ffffff;
    padding: 20px;
    height: calc(100vh - 60px);
}
.idle-viewcount {
    font-size: 12px;
    color: #888;
    margin-top: 4px;

    white-space: normal; /* ✅ 允许换行显示 */
    word-break: break-word; /* ✅ 长词自动断行 */
    overflow: visible; /* ✅ 防止隐藏 */
    text-overflow: initial;
}
</style>
